<template>
  <div class="floating-chat">
    <div class="chat-button" @click="toggleChat" :class="{ active: showChat }">
      <i class="el-icon-chat-dot-round"></i>
    </div>
    
    <transition name="slide">
      <div class="chat-window" v-if="showChat">
        <div class="chat-header">
          <div class="service-info">
            <el-avatar :size="30" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"></el-avatar>
            <div class="service-detail">
              <div class="service-name">客服小王</div>
              <div class="service-status online">在线</div>
            </div>
          </div>
          <div class="header-actions">
            <i class="el-icon-close" @click="toggleChat"></i>
          </div>
        </div>
        
        <div class="chat-messages" ref="messageBox">
          <div v-for="(message, index) in messages" :key="index" :class="['message', message.type]">
            <template v-if="message.type === 'service'">
              <el-avatar :size="30" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"></el-avatar>
              <div class="message-content">
                <div class="message-text">{{ message.content }}</div>
                <div class="message-time">{{ message.time }}</div>
              </div>
            </template>
            <template v-else>
              <div class="message-content">
                <div class="message-text">{{ message.content }}</div>
                <div class="message-time">{{ message.time }}</div>
              </div>
              <el-avatar :size="30" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
            </template>
          </div>
        </div>
        
        <div class="chat-input">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入消息..."
            v-model="inputMessage"
            @keyup.enter.native="sendMessage"
          ></el-input>
          <div class="input-actions">
            <el-button size="small" type="primary" @click="sendMessage" :disabled="!inputMessage.trim()">发送</el-button>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
export default {
  name: 'FloatingChat',
  data() {
    return {
      showChat: false,
      inputMessage: '',
      messages: [
        {
          type: 'service',
          content: '您好，我是客服小王，很高兴为您服务，请问有什么可以帮助您的吗？',
          time: this.formatTime(new Date())
        }
      ],
      websocket: null,
      sessionId: null,
      userId: null,
      serviceId: 1, // 默认客服ID
      heartbeatTimer: null,
      reconnectTimer: null,
      reconnectAttempts: 0,
      maxReconnectAttempts: 5
    }
  },
  created() {
    // 获取用户ID，实际项目中应从登录用户信息中获取
    this.userId = localStorage.getItem('userId') || Math.floor(Math.random() * 1000000);
    localStorage.setItem('userId', this.userId);
  },
  mounted() {
    // 连接WebSocket
    this.connectWebSocket();
  },
  beforeDestroy() {
    // 关闭WebSocket连接
    this.closeWebSocket();
  },
  watch: {
    showChat(val) {
      if (val) {
        this.$nextTick(() => {
          this.scrollToBottom();
        })
      }
    }
  },
  methods: {
    toggleChat() {
      this.showChat = !this.showChat;
      if (this.showChat && !this.websocket) {
        this.connectWebSocket();
      }
    },
    sendMessage() {
      if (!this.inputMessage.trim()) return;
      
      // 添加用户消息
      const userMessage = {
        type: 'user',
        content: this.inputMessage,
        time: this.formatTime(new Date())
      };
      this.messages.push(userMessage);
      
      // 发送消息到服务器
      if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
        const message = {
          type: 'CHAT',
          sessionId: this.sessionId,
          receiverId: this.serviceId,
          content: this.inputMessage,
          timestamp: Date.now()
        };
        this.websocket.send(JSON.stringify(message));
      } else {
        // WebSocket未连接，使用自动回复
        setTimeout(() => {
          this.receiveServiceMessage(this.getAutoReply(this.inputMessage));
        }, 1000);
      }
      
      // 清空输入框
      this.inputMessage = '';
    },
    receiveServiceMessage(content) {
      const serviceMessage = {
        type: 'service',
        content,
        time: this.formatTime(new Date())
      };
      this.messages.push(serviceMessage);
      this.scrollToBottom();
    },
    formatTime(date) {
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const messageBox = this.$refs.messageBox;
        if (messageBox) {
          messageBox.scrollTop = messageBox.scrollHeight;
        }
      });
    },
    getAutoReply(message) {
      // 简单的自动回复逻辑
      const lowerMessage = message.toLowerCase();
      
      if (lowerMessage.includes('你好') || lowerMessage.includes('hi') || lowerMessage.includes('hello')) {
        return '您好，请问有什么可以帮助您的吗？';
      }
      
      if (lowerMessage.includes('价格') || lowerMessage.includes('多少钱') || lowerMessage.includes('费用')) {
        return '我们的租车价格根据车型不同而有所差异，经济型轿车一般每天200-300元，SUV每天300-500元，豪华车型每天500元起。具体价格请在车辆详情页查看。';
      }
      
      if (lowerMessage.includes('押金') || lowerMessage.includes('保证金')) {
        return '我们的押金政策是：经济型轿车2000元，中高级轿车3000-5000元，豪华车型10000元起。押金在还车时会全额退还（如无违章和车辆损伤）。';
      }
      
      if (lowerMessage.includes('取车') || lowerMessage.includes('还车') || lowerMessage.includes('门店')) {
        return '您可以在我们全国各大城市的门店取还车，目前已覆盖北京、上海、广州、深圳等50多个城市，200多家门店。具体门店地址可在下单时选择查看。';
      }
      
      return '您的问题我已收到，稍后会有专业客服人员与您联系解答。您也可以拨打我们的客服热线：400-123-4567，获取更多帮助。';
    },
    
    // WebSocket相关方法
    connectWebSocket() {
      // 检查浏览器是否支持WebSocket
      if ('WebSocket' in window) {
        // 创建WebSocket连接
        const wsUrl = `ws://${window.location.hostname}:8086/service/ws/chat/${this.userId}/1`;
        this.websocket = new WebSocket(wsUrl);
        
        // 连接成功
        this.websocket.onopen = () => {
          console.log('WebSocket连接成功');
          this.reconnectAttempts = 0;
          
          // 发送心跳包
          this.startHeartbeat();
          
          // 发送连接消息
          const connectMessage = {
            type: 'CONNECT',
            senderId: this.userId,
            senderType: 1,
            timestamp: Date.now()
          };
          this.websocket.send(JSON.stringify(connectMessage));
        };
        
        // 接收消息
        this.websocket.onmessage = (event) => {
          const message = JSON.parse(event.data);
          console.log('收到消息:', message);
          
          // 处理不同类型的消息
          switch (message.type) {
            case 'CONNECT':
              // 连接成功，保存会话ID
              if (message.sessionId) {
                this.sessionId = message.sessionId;
              }
              break;
            case 'CHAT':
              // 接收聊天消息
              if (message.senderType === 2) { // 客服消息
                this.receiveServiceMessage(message.content);
              }
              break;
            case 'HEARTBEAT':
              // 心跳响应，不做处理
              break;
            default:
              break;
          }
        };
        
        // 连接关闭
        this.websocket.onclose = () => {
          console.log('WebSocket连接关闭');
          this.stopHeartbeat();
          
          // 尝试重连
          if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectTimer = setTimeout(() => {
              this.reconnectAttempts++;
              console.log(`尝试第${this.reconnectAttempts}次重连`);
              this.connectWebSocket();
            }, 3000);
          }
        };
        
        // 连接错误
        this.websocket.onerror = (error) => {
          console.error('WebSocket连接错误:', error);
        };
      } else {
        console.error('浏览器不支持WebSocket');
      }
    },
    
    closeWebSocket() {
      if (this.websocket) {
        // 发送关闭消息
        const closeMessage = {
          type: 'CLOSE',
          sessionId: this.sessionId,
          senderId: this.userId,
          senderType: 1,
          timestamp: Date.now()
        };
        
        try {
          this.websocket.send(JSON.stringify(closeMessage));
        } catch (e) {
          console.error('发送关闭消息失败:', e);
        }
        
        // 关闭连接
        this.websocket.close();
        this.websocket = null;
        
        // 停止心跳
        this.stopHeartbeat();
        
        // 清除重连定时器
        if (this.reconnectTimer) {
          clearTimeout(this.reconnectTimer);
          this.reconnectTimer = null;
        }
      }
    },
    
    startHeartbeat() {
      this.heartbeatTimer = setInterval(() => {
        if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
          const heartbeatMessage = {
            type: 'HEARTBEAT',
            timestamp: Date.now()
          };
          this.websocket.send(JSON.stringify(heartbeatMessage));
        }
      }, 30000); // 30秒发送一次心跳
    },
    
    stopHeartbeat() {
      if (this.heartbeatTimer) {
        clearInterval(this.heartbeatTimer);
        this.heartbeatTimer = null;
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.floating-chat {
  position: fixed;
  right: 20px;
  bottom: 20px;
  z-index: 1000;
  
  .chat-button {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    background-color: #409EFF;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    transition: all 0.3s;
    
    i {
      font-size: 24px;
    }
    
    &:hover {
      transform: scale(1.05);
      background-color: #66b1ff;
    }
    
    &.active {
      transform: scale(0);
      opacity: 0;
    }
  }
  
  .chat-window {
    position: fixed;
    right: 20px;
    bottom: 20px;
    width: 350px;
    height: 450px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    overflow: hidden;
    
    .chat-header {
      padding: 10px 15px;
      border-bottom: 1px solid #ebeef5;
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .service-info {
        display: flex;
        align-items: center;
        
        .service-detail {
          margin-left: 10px;
          
          .service-name {
            font-size: 14px;
            font-weight: 500;
            color: #303133;
          }
          
          .service-status {
            font-size: 12px;
            
            &.online {
              color: #67c23a;
              
              &:before {
                content: '';
                display: inline-block;
                width: 6px;
                height: 6px;
                border-radius: 50%;
                background-color: #67c23a;
                margin-right: 5px;
              }
            }
          }
        }
      }
      
      .header-actions {
        i {
          font-size: 18px;
          color: #909399;
          cursor: pointer;
          
          &:hover {
            color: #606266;
          }
        }
      }
    }
    
    .chat-messages {
      flex: 1;
      padding: 15px;
      overflow-y: auto;
      background-color: #f5f7fa;
      
      .message {
        display: flex;
        margin-bottom: 15px;
        
        &.service {
          align-items: flex-start;
          
          .el-avatar {
            margin-right: 8px;
          }
          
          .message-content {
            .message-text {
              background-color: #fff;
              color: #606266;
              border-radius: 0 8px 8px 8px;
            }
          }
        }
        
        &.user {
          justify-content: flex-end;
          align-items: flex-start;
          
          .el-avatar {
            margin-left: 8px;
          }
          
          .message-content {
            align-items: flex-end;
            
            .message-text {
              background-color: #409eff;
              color: #fff;
              border-radius: 8px 0 8px 8px;
            }
            
            .message-time {
              text-align: right;
            }
          }
        }
        
        .message-content {
          max-width: 70%;
          display: flex;
          flex-direction: column;
          
          .message-text {
            padding: 8px 12px;
            word-break: break-word;
            line-height: 1.5;
            font-size: 14px;
          }
          
          .message-time {
            font-size: 11px;
            color: #909399;
            margin-top: 3px;
          }
        }
      }
    }
    
    .chat-input {
      padding: 10px 15px;
      border-top: 1px solid #ebeef5;
      
      .input-actions {
        display: flex;
        justify-content: flex-end;
        margin-top: 8px;
      }
    }
  }
}

.slide-enter-active, .slide-leave-active {
  transition: all 0.3s;
}

.slide-enter, .slide-leave-to {
  opacity: 0;
  transform: translateY(20px);
}
</style> 